from dns.dnssec import validate
from fastapi import HTTPException, status
from sqlalchemy.exc import SQLAlchemyError

from handle.handle_log import log
from server.controller.log import create_log
from server.db.models.system import User
from utils.password_validate import password_validate
from utils.security import get_password_hash


def create_user(request, user, db, current_user):
    """
    添加用户
    :param current_user:
    :param request:
    :param user:
    :param db:
    :return:
    """
    # 检查用户是否存在
    existing_user = db.query(User).filter(
        User.username == user.username,
        User.is_deleted == False
    ).first()
    if existing_user:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(user),
            ip_address=request.client.host,
            user_agent=request.headers.get('User-Agent'),
            status_code=1400,
            response="用户已存在"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1400, "msg": "用户已存在"}
        )
    # 校验密码规则
    validate_pwd = password_validate(user.password)
    if not validate_pwd:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(user),
            ip_address=request.client.host,
            user_agent=request.headers.get('User-Agent'),
            status_code=1400,
            response="密码长度大于8且必须为数值、大小写字母、特殊字符组合"
        )
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail={"code": 1400, "msg": "密码长度大于8且必须为数值、大小写字母、特殊字符组合"}
        )

    # 创建新用户
    try:
        new_user = User(
            username=user.username,
            password=get_password_hash(user.password),
            phone=user.phone,
            real_name=user.real_name,
            is_active=user.is_active,
            is_superuser=user.is_superuser
        )
        db.add(new_user)
        db.commit()
        db.refresh(new_user)
    except Exception as e:
        db.rollback()
        log.error(e)
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(user),
            ip_address=request.client.host,
            user_agent=request.headers.get('User-Agent'),
            status_code=1500,
            response="创建用户失败"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )
    else:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(user),
            ip_address=request.client.host,
            user_agent=request.headers.get('User-Agent'),
            status_code=200,
            response="操作成功"
        )
        return {"code": 200, "msg": "操作成功"}


def get_info(request, userid: str, db, current_user):
    """
    获取用户信息
    :param request:
    :param userid:
    :param db:
    :return:
    """
    query = db.query(User).filter(User.is_deleted == False)
    if userid == "" or userid is None:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail={"code": 1503, "msg": "参数错误"}
        )

    try:
        # 直接按字符串查询（因为数据库 id 是 String 类型）
        user = query.filter(User.id == userid).first()

        if not user:
            # 用户不存在，记录日志并返回 1404
            create_log(
                db=db,
                user_id=current_user,
                method=request.method,
                path=str(request.url),
                params=str(request.path_params),
                ip_address=request.client.host,
                status_code=1404,
                user_agent=request.headers.get("User-Agent"),
                response="用户不存在"
            )
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail={"code": 1404, "msg": "用户不存在"}
            )

        # 用户存在，记录成功日志
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(request.path_params),
            ip_address=request.client.host,
            status_code=200,
            user_agent=request.headers.get("User-Agent"),
            response="操作成功"
        )
        response = {
            "userid": user.id,
            "username": user.username,
            "phone": user.phone,
            "real_name": user.real_name,
            "is_superuser": user.is_superuser,
            "is_active": user.is_active,
            "created_at": user.created_at,
            "updated_at": user.updated_at,
            "avatar": user.avatar
        }
        return {"data": response, "code": 200, "msg": "操作成功"}

    except SQLAlchemyError as e:
        # 数据库错误，记录系统错误日志
        log.error(f"数据库查询失败: {e}")
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(request.path_params),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )



def get_user_list(request, page, db, current_user):
    """
    获取户列表
    :param request:
    :param page:
    :param db:
    :return:
    """
    try:
        query = db.query(User).filter(User.is_deleted == False).offset((page.page - 1) * page.size).limit(page.size)
        user_list = query.all()
    except SQLAlchemyError as e:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(request.path_params),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        log.error(f"{e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )
    else:
        user_list_ = []
        for user in user_list:
            user_list_.append({
                "id": user.id,
                "username": user.username,
                "phone": user.phone,
                "real_name": user.real_name,
                "is_superuser": user.is_superuser,
                "is_active": user.is_active,
                "created_at": user.created_at,
                "updated_at": user.updated_at,
            })
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(user_list),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="操作成功"
        )
        return {"data": user_list_, "code": 200, "msg": "操作成功"}


def update_user_info(request, user, db, current_user):
    """
    更新用户信息
    :param request:
    :param user:
    :param db:
    :return:
    """
    try:
        db.query(User).filter(User.id == user.id).update(
            {
                User.username: user.username,
                User.phone: user.phone,
                User.real_name: user.real_name,
                User.is_superuser: user.is_superuser,
                User.is_active: user.is_active,
            }
        )
        db.commit()
    except SQLAlchemyError as e:
        log.error(f"{e}")
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(user),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )
    else:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(user),
            ip_address=request.client.host,
            status_code=200,
            user_agent=request.headers.get("User-Agent"),
            response="操作成功"
        )
        return {"code": 200, "msg": "操作成功"}

def delete_user_for_id(request, userid, db, current_user):
    """
    删除用户
    :param request:
    :param userid:
    :param db:
    :return:
    """

    try:
        db.query(User).filter(User.id == userid.id).update(
            {User.is_deleted: True}
        )
        db.commit()
    except SQLAlchemyError as e:
        log.error(f"{e}")
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(userid),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )
    else:

        create_log(
                db=db,
                user_id=current_user,
                method=request.method,
                path=str(request.url),
                params=str(userid),
                ip_address=request.client.host,
                status_code=200,
                user_agent=request.headers.get("User-Agent"),
                response="操作成功"
            )
        return {"code": 200, "msg": "操作成功"}





def reset_user_password(request, userid, db, current_user):
    """
    重置密码
    :param request:
    :param userid:
    :param db:
    :return:
    """
    try:
        db.query(User).filter(User.id == userid.id).update(
            {User.password: get_password_hash("Test@654321")}
        )
        db.commit()
    except SQLAlchemyError as e:
        log.error(f"{e}")
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(userid.id),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )
    else:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(userid.id),
            ip_address=request.client.host,
            status_code=200,
            user_agent=request.headers.get("User-Agent"),
            response="操作成功"
        )
        return {"code": 200, "msg": "操作成功"}

